home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7271 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.vais.net!news
  2. From: Chalrie Fink <cfink@aecsoft.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Any way to restrict casting?
  5. Date: Thu, 22 Feb 1996 08:34:25 -0500
  6. Organization: AEC Software
  7. Message-ID: <312C70E1.44AE@aecsoft.com>
  8. References: <4gfuj4$1cu@news.mistral.co.uk>
  9. NNTP-Posting-Host: pm01-s07.vais.net
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (Win95; I)
  14.  
  15. Alan Campbell wrote:
  16. > Using Borland C++ 3.1, I find I can coerce a pointer to an instance of
  17. > a class into a pointer to *anything*.  Like an int.
  18. > e.g.:
  19. > #include <iostream.h>
  20. > #include <string.h>
  21. > class Base {
  22. > public:
  23. >    int iFieldb;
  24. >    char cFieldb;
  25. >    char sFieldb[10];
  26. > };
  27. > class Derived: public Base {
  28. > public:
  29. >    int iFieldd;
  30. >    char cFieldd;
  31. >    char sFieldd[10];
  32. > };
  33. > int main()
  34. >   {
  35. >    Base aBase;
  36. >    Derived aDerived;
  37. >    aBase.iFieldb = 10;
  38. >    aBase.cFieldb = 'a';
  39. >    strcpy(aBase.sFieldb,"abcdefghi");
  40. >    aDerived.iFieldd = 210;
  41. >    aDerived.cFieldd = 'ba';
  42. >    strcpy(aDerived.sFieldd,"jklmnopqr");
  43. >    Base* ptrBase = &aBase;
  44. >    cout << "aDerived's sFieldb: " <<  ptrBase->sFieldb  << endl;
  45. >    Derived*  ptrDerived = &aDerived;
  46. >    cout << "aDerived's sFieldd: " << ptrDerived->sFieldd  << endl;
  47. > // this is stupid, but it works
  48. >    ptrDerived =  (Derived*) ptrBase;
  49. >    cout << "aBase's sFieldd, treated as a Derived: " <<
  50. >      ptrDerived->sFieldd  << endl;
  51. >    int anInt;
  52. > // this is even stupider; taking a data member of an int!
  53. >    ptrDerived =  (Derived*) &anInt;
  54. >    cout << "anInt's sFieldd, treated as a Derived: " <<
  55. >      ptrDerived->sFieldd  << endl;
  56. >    return 1;
  57. >   };
  58. > Is this valid in all dialects of C++?  Is it part of the standard?  If
  59. > so, ouch.
  60. > Yours,
  61. > Alan Campbell
  62. > Brighton, UK
  63. > <<<<<<<<<<<<<<<<<<<<<<     >>>>>>>>>>>>>>>>>>>
  64.  
  65. Allan:
  66.  
  67. If you don't like it, just don't do it!
  68.